import { decryptByDESModeEBC, encryptByDESModeEBC } from '@/common/encrypt';
import http from '@/common/http';
import { Dialog } from 'mand-mobile';
import Loading from '@/components/loading';
function pySegSort(arr) {
  var letters = '*ABCDEFGHJKLMNOPQRSTWXYZ'.split('');
  var zh = '阿吧嚓哒妸发旮哈讥咔垃妈拏噢妑七呥扨它穵夕丫帀'.split('');
  var segs = [];
  var curr;
  letters.forEach(function(item, i) {
    curr = {
      letter: item,
      data: []
    };
    arr.forEach(function(obj) {
      let item2 = obj.city;
      let p = pinyinUtil.getFirstLetter(item2[0]);
      if (item === p) {
        curr.data.push(obj);
      }
    });
    if (curr.data.length) {
      segs.push(curr);
    }
  });
  return segs;
}
const defaultState = () => {
  return {
    hasTaxi: true,
    appointmentInfo: null,
    redMoneyInfo: null,
    taxiOrderInfo: null,
    callTaxiInfo: null,
    indexInfo: null,
    modifyRedMoneyInfo: null,
    taxiValuationMethodInfo: null,
    taxiSubmitPaymentInfo: null,
    taxiGetDoOrderInfo: null,
    taxiOrderStatus: '', // 订单状态
    taxiBottomType: '0', // 底部显示状态
    citys: [], // 从服务器获取的开通出租车的城市列表
    sortedCitys: [],
    selectedCity: null,
    historyList: [],
    startPosition: {
      // 出租车起点信息
      start_pst: '',
      start_pst_detail: '',
      start_lnglat: ''
    },
    endPosition: {
      // 出租车目的地信息
      end_pst: '',
      end_pst_detail: '',
      end_lnglat: ''
    },
    currentGpsPosition: '',
    nearDriverList: []
  };
};
const state = defaultState();
const actions = {
  getHasTaxi(context, currentCity) {
    return new Promise((resolve, reject) => {
      let params = {
        city: currentCity
      };
      Loading.show();
      http.post('pakj/common/getBusOpen', params).then(res => {
        Loading.hide();
        if (res.data.code === '000000') {
          context.commit('setHasTaxi', res.data.data);
          resolve();
        } else {
          Dialog.alert({
            title: '提示',
            content: res.data.msg,
            confirmText: '确定'
          });
          reject(new Error(res.data.code + ':' + res.data.msg));
        }
      });
    });
  },
  getTaxiCitys(context) {
    return new Promise((resolve, reject) => {
      Loading.show();
      http.post('pakj/utaxi/getAllCity').then(res => {
        Loading.hide();
        if (res.data.code === '000000') {
          context.commit('setTaxiCitys', res.data.data);
          resolve();
        } else {
          Dialog.alert({
            title: '提示',
            content: res.data.msg,
            confirmText: '确定'
          });
          reject(new Error(res.data.code + ':' + res.data.msg));
        }
      });
    });
  },
  getIndexInfo(context) {
    return new Promise((resolve, reject) => {
      Loading.show();
      http.post('pakj/passenger/getIndexInfo').then(res => {
        Loading.hide();
        if (res.data.code === '000000') {
          context.commit('setIndexInfo', res.data.data.show_view.others);
          resolve();
        } else {
          Dialog.alert({
            title: '提示',
            content: res.data.msg,
            confirmText: '确定'
          });
          reject(new Error(res.data.code + ':' + res.data.msg));
        }
      });
    });
  },
  getappointment(context) {
    return new Promise((resolve, reject) => {
      Loading.show();
      http.post('pakj/utaxi/getTaxiOrderTime').then(res => {
        Loading.hide();
        if (res.data.code === '000000') {
          console.log(res.data);
          context.commit('setgetappointment', res.data.data);
          resolve();
        } else {
          Dialog.alert({
            title: '提示',
            content: res.data.msg,
            confirmText: '确定'
          });
          reject(new Error(res.data.code + ':' + res.data.msg));
        }
      });
    });
  },
  getRedMoney(context) {
    return new Promise((resolve, reject) => {
      Loading.show();
      http.post('/pakj/utaxi/getRewardMoney').then(res => {
        Loading.hide();
        if (res.data.code === '000000') {
          context.commit('setRedMoney', res.data.data);
          resolve();
        } else {
          Dialog.alert({
            title: '提示',
            content: res.data.msg,
            confirmText: '确定'
          });
          reject(new Error(res.data.code + ':' + res.data.msg));
        }
      });
    });
  },
  getModifyRedMoney(context, params) {
    return new Promise((resolve, reject) => {
      Loading.show();
      http.post('/pakj/utaxi/updateOrderReward', params).then(res => {
        Loading.hide();
        if (res.data.code === '000000') {
          context.commit('setModifyRedMoney', res.data.data);
          resolve();
        } else {
          Dialog.alert({
            title: '提示',
            content: res.data.msg,
            confirmText: '确定'
          });
          reject(new Error(res.data.code + ':' + res.data.msg));
        }
      });
    });
  },
  getTaxiOrderInfo(context, orderno) {
    return new Promise((resolve, reject) => {
      Loading.show();
      let params = {
        order_no: orderno
      };
      http.post('/pakj/utaxi/getOrderById', params).then(res => {
        Loading.hide();
        if (res.data.code === '000000') {
          context.commit('setTaxiOrderInfo', res.data.data);
          resolve();
        } else {
          Dialog.alert({
            title: '提示',
            content: res.data.msg,
            confirmText: '确定'
          });
          reject(new Error(res.data.code + ':' + res.data.msg));
        }
      });
    });
  },
  getCallTaxi(context, params) {
    return new Promise((resolve, reject) => {
      Loading.show();
      http.post('/pakj/utaxi/createOrder', params).then(res => {
        Loading.hide();
        if (res.data.code === '000000') {
          context.commit('setCallTaxi', res.data.data);
          resolve();
        } else if (res.data.code === '250250') {
          // 判断选择的预约时间
          reject(new Error(res.data.code + ':' + res.data.msg));
        } else {
          Dialog.alert({
            title: '提示',
            content: res.data.msg,
            confirmText: '确定'
          });
          reject(new Error(res.data.code + ':' + res.data.msg));
        }
      });
    });
  },
  getTaxiValuationMethod(context, params) {
    return new Promise((resolve, reject) => {
      Loading.show();
      http.post('/pakj/utaxi/getTaxiPMode', params).then(res => {
        Loading.hide();
        if (res.data.code === '000000') {
          context.commit('setTaxiValuationMethod', res.data.data);
          resolve();
        } else {
          Dialog.alert({
            title: '提示',
            content: res.data.msg,
            confirmText: '确定'
          });
          reject(new Error(res.data.code + ':' + res.data.msg));
        }
      });
    });
  },
  getTaxiHistoryList(context, selected) {
    return new Promise((resolve, reject) => {
      Loading.show();
      let params = {
        address: selected
      };
      http.post('pakj/utaxi/getHisAddress', params).then(res => {
        Loading.hide();
        if (res.data.code === '000000') {
          context.commit('setTaxiHistoryList', res.data.data);
          resolve();
        } else {
          Dialog.alert({
            title: '提示',
            content: res.data.msg,
            confirmText: '确定'
          });
          reject(new Error(res.data.code + ':' + res.data.msg));
        }
      });
    });
  },
  taxiSubmitPayment(context, params) {
    return new Promise((resolve, reject) => {
      Loading.show();
      http.post('/pakj/utaxi/payOrder', params).then(res => {
        Loading.hide();
        if (res.data.code === '000000') {
          context.commit('setTaxiSubmitPayment', res.data.data);
          resolve();
        } else if (res.data.code === '200008') {
          Dialog.alert({
            title: '错误',
            content: '请不要重复支付',
            onConfirm: () => {
              reject(new Error('200008'));
            }
          });
        } else {
          Dialog.alert({
            title: '提示',
            content: res.data.msg,
            confirmText: '确定'
          });
          reject(new Error(res.data.code + ':' + res.data.msg));
        }
      });
    });
  },
  taxiGetDoOrder(context, params) {
    return new Promise((resolve, reject) => {
      Loading.show();
      http.post('pakj/utaxi/getDoOrder', params).then(res => {
        Loading.hide();
        if (res.data.code === '000000') {
          context.commit('setTaxiGetDoOrder', res.data.data);
          resolve();
        } else {
          reject(new Error(res.data.msg));
        }
      });
    });
  },
  getTaxiNearDrivers(context, lnglat) {
    return new Promise((resolve, reject) => {
      Loading.show();
      let params = {
        lnglat: encryptByDESModeEBC(lnglat)
      };
      http.post('pakj/utaxi/getNearDriver', params).then(res => {
        Loading.hide();
        if (res.data.code === '000000') {
          context.commit('setNearDrivers', res.data.data);
          resolve();
        } else {
          Dialog.alert({
            title: '提示',
            content: res.data.msg,
            confirmText: '确定'
          });
          reject(new Error(res.data.code + ':' + res.data.msg));
        }
      });
    });
  }
};
const mutations = {
  resetTaxi(state) {
    Object.assign(state, defaultState());
  },
  setTaxiCitys(state, citys) {
    state.citys = citys;
    state.sortedCitys = pySegSort(citys);
  },
  setTaxiSelectedCity(state, city) {
    state.selectedCity = city;
  },
  setHasTaxi(state, data) {
    if (data.taxi === '1') {
      state.hasTaxi = true;
    }
  },
  setgetappointment(state, data) {
    console.log('获取预约时间列表：', data);
    state.appointmentInfo = data;
  },
  setRedMoney(state, data) {
    console.log('获取红包列表：', data);
    state.redMoneyInfo = data;
  },
  setModifyRedMoney(state, data) {
    console.log('获取修改红包列表：', data);
    state.modifyRedMoneyInfo = data;
  },
  setTaxiGetDoOrder(state, data) {
    console.log('获取出租车列表：', data);
    state.taxiGetDoOrderInfo = data;
  },
  setTaxiStartPosition(state, data) {
    state.startPosition = data;
  },
  setTaxiEndPosition(state, data) {
    state.endPosition = data;
  },
  resetTaxiStartPosition(state) {
    state.startPosition = {
      // 出租车起点信息
      start_pst: '',
      start_pst_detail: '',
      start_lnglat: ''
    };
  },
  resetTaxiEndPosition(state) {
    state.endPosition = {
      // 出租车目的地信息
      end_pst: '',
      end_pst_detail: '',
      end_lnglat: ''
    };
  },
  setTaxiOrderInfo(state, data) {
    if (data) {
      data.start_lnglat = decryptByDESModeEBC(data.start_lnglat);
    }
    if (data) {
      data.end_lnglat = decryptByDESModeEBC(data.end_lnglat);
    }
    console.log('获取订单详情：', data);
    state.taxiOrderInfo = data;
  },
  setCallTaxi(state, data) {
    console.log('下单信息：', data);
    state.callTaxiInfo = data;
  },
  setTaxiOrderStatus(state, data) {
    console.log('订单状态：', data);
    state.taxiOrderStatus = data;
  },
  setTaxiBottomType(state, data) {
    console.log('底部显示状态：', data);
    state.taxiBottomType = data;
  },
  setTaxiValuationMethod(state, data) {
    console.log('显示计价方式：', data);
    state.taxiValuationMethodInfo = data;
  },
  setTaxiSubmitPayment(state, data) {
    console.log('支付方式：', data);
    state.taxiSubmitPaymentInfo = data;
  },
  setIndexInfo(state, data) {
    if (data instanceof Array) {
      if (data.length > 0) {
        data.forEach((item, index) => {
          switch (item.name) {
            case '城际出行':
              item.routeName = 'Home';
              break;
            case '市内用车':
              item.routerName = 'homeIncity';
              break;
            case '出租车':
              item.routerName = 'homeTaxi';
              break;
            case '顺风车':
              item.routerName = 'homeHitchhike';
              break;
          }
        });
      }
    }
    console.log('头部业务开关：', data);
    state.indexInfo = data;
  },
  setTaxiHistoryList(state, data) {
    let arr = [];
    if (Array.isArray(data)) {
      data.forEach((item, index) => {
        let obj = {
          stationName: item.address,
          position: item.address_detail,
          coordinate: decryptByDESModeEBC(item.lnglat),
          city: item.city
        };
        arr.push(obj);
      });
    }
    state.historyList = arr;
  },
  setCurrentGpsPosition(state, position) {
    state.currentGpsPosition = position;
    localStorage.setItem('DRIVER_GPS', position);
  },
  clearGpsPosition(state) {
    state.currentGpsPosition = '';
    localStorage.removeItem('DRIVER_GPS');
  },
  setNearDrivers(state, data) {
    state.nearDriverList = data;
    console.log('当前附近出租车司机数量：', data.length);
  }
};
const getters = {
  hasTaxi(state) {
    return state.hasTaxi;
  },
  taxiCitys(state) {
    return state.citys;
  },
  taxiSortedCitys(state) {
    return state.sortedCitys;
  },
  taxiSelectedCity(state) {
    return state.selectedCity;
  },
  getappointmentData(state) {
    return state.appointmentInfo;
  },
  getRedMoneyData(state) {
    return state.redMoneyInfo;
  },
  getmodifyRedMoneyData(state) {
    return state.modifyRedMoneyInfo;
  },
  getTaxiStatus(state) {
    return state.taxiOrderStatus;
  },
  getTaxiBottomType(state) {
    return state.taxiBottomType;
  },
  getTtaxiDoOrderData(state) {
    return state.taxiGetDoOrderInfo;
  },
  taxiStartPosition(state) {
    if (state.startPosition.start_lnglat === '' && state.taxiOrderInfo) {
      return {
        start_lnglat: state.taxiOrderInfo.start_lnglat,
        start_pst: state.taxiOrderInfo.start_pst,
        start_pst_detail: state.taxiOrderInfo.start_pst_detail
      };
    }
    return state.startPosition;
  },
  taxiEndPosition(state) {
    if (state.endPosition.end_lnglat === '' && state.taxiOrderInfo) {
      return {
        end_lnglat: state.taxiOrderInfo.end_lnglat,
        end_pst: state.taxiOrderInfo.end_pst,
        end_pst_detail: state.taxiOrderInfo.end_pst_detail
      };
    }
    return state.endPosition;
  },
  getTaxiOrderInfoData(state) {
    return state.taxiOrderInfo;
  },
  getCallTaxiData(state) {
    return state.callTaxiInfo;
  },
  getTaxiValuationMethod(state) {
    return state.taxiValuationMethodInfo;
  },
  taxiHistoryList(state) {
    return state.historyList;
  },
  getIndexInfoData(state) {
    return state.indexInfo;
  },
  taxiSubmitPaymentData(state) {
    return state.taxiSubmitPaymentInfo;
  },
  getTaxiOrderTopic(state) {
    if (state.taxiOrderInfo) {
      return state.taxiOrderInfo.order_topic;
    }
    return undefined;
  },
  getTaxiGpsTopic(state) {
    if (state.taxiOrderInfo) {
      return state.taxiOrderInfo.gps_topic;
    }
    return undefined;
  },
  currentGpsPosition(state) {
    if (state.currentGpsPosition === '') {
      let str = localStorage.getItem('DRIVER_GPS');
      if (str && str !== '') {
        state.currentGpsPosition = str;
      }
    }
    return state.currentGpsPosition;
  },
  taxiNearDrivers(state) {
    return state.nearDriverList;
  }
};
export default {
  state,
  actions,
  mutations,
  getters
};
